package cz.vse.javaee.album;

import javax.ejb.EJB;
import javax.swing.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * <p/>
 * Created by IntelliJ IDEA.
 * User: zslajchrt
 * Date: Apr 21, 2010
 * Time: 9:37:38 PM
 */
public class Main {

    @EJB
    private static AlbumDAORemote albumDAO;

    public static void main(String[] args) throws NoPhotoFoundException, IOException {
        if (args.length == 1 && "-l".equals(args[0])) {
            listPhotos();
        } else if (args.length == 3 && "-d".equals(args[0])) {
            download(args);
        } else {
            JOptionPane.showMessageDialog(null, "Parameters: (-l | -d photoName file).");
        }
    }

    private static void download(String[] args) throws NoPhotoFoundException, IOException {
        String photoName = args[1];
        Photo photo = albumDAO.findPhoto(photoName);
        byte[] bytes = photo.getImage();
        File photoFile = new File(args[2]);

        FileOutputStream fos = new FileOutputStream(photoFile);
        fos.write(bytes);
        fos.close();

        JOptionPane.showMessageDialog(null, "Downloaded photo " + photoName + " to " + photoFile);
    }

    private static void listPhotos() {
        StringBuilder sb = new StringBuilder();
        List<Photo> photos = albumDAO.getPhotos();
        for (Photo photo : photos) {
            sb.append(photo.getName()).append('\n');
        }
        JOptionPane.showMessageDialog(null, "Fotky:\n" + sb.toString());
    }
}



